////////////////////////////////////////////////////////////
// Workfile : Reader.cpp
// Author : Andreas Lehner
// Date : 5.11.2012
// Description : reads a given file (address or person) IMPLEMENTATION
// Remarks : 0
// Revision : 1
////////////////////////////////////////////////////////////
#include "Reader.h"
#include <fstream>
#include <string>
#include <sstream>

using namespace std;

//read a address-file or person-file
void Reader::ReadFile(string const& filename, IRead *read){
	size_t count = 0;
	string line;
	string comment = "#";
	//file stream
	ifstream file;
	//open file
	file.open(filename);
	if (file.is_open()){
		//read line by line until eof
		while(!file.eof()){
			getline(file, line);
			if (line.size() == 0){
				throw "ReadFile: line is empty...";
			}
			//read line (address or person) if its not a comment
			if (line[0] != comment[0]){
				DoRead(line, read);
				count++;
			}
		}
	}else{
		throw "ReadFile: Not able to open file...";
	}
	if (count == 0){
		throw "ReadFile: file is empty...";
	}
	//close file
	file.close();
}
//function to check if string is a number
bool Reader::isNumber(string const& str) const{
	for(size_t i = 0; i < str.size(); ++i){
		//check for a number between 0-9
		if(str[i] < '0' || str[i] > '9'){
			return false;
		}
	}
	return true;
}
//read a word of a string
string Reader::readWord(string::const_iterator & start, string::const_iterator const& end) const{
	stringstream ss;
	//read a word (read until a blank is reached)
	for(; start != end; ++start){
		if (*start == ' '){
			++start;
			//a word is not a number
			if(isNumber(ss.str())){
				throw "readWord: word expected...";
			}else{
				return ss.str();
			}
		}else{
			//add character to stringstream
			ss << *start;
		}
	}
	if(isNumber(ss.str())){
		throw "readWord: word expected...";
	}else{
		return ss.str();
	}
}
//read a number of a string
size_t Reader::readNumber(string::const_iterator & start, string::const_iterator const& end) const{
	stringstream ss;
	//read a word (read until a blank is reached)
	for(; start != end; ++start){
		if (*start == ' '){
			++start;
			//check if a string is a number
			if (isNumber(ss.str())){
				return size_t(atoi(ss.str().c_str()));
			}else{
				throw "readNumber: number expected...";
			}
		}else{
			//add character to stringstream
			ss << *start;
		}
	}
	if (isNumber(ss.str())){
		return size_t(atoi(ss.str().c_str()));
	}else{
		throw "readNumber: number expected...";
	}
}